<?php
require_once '../../config/database.php';
require_once '../../includes/operation_logger.php';

// JSON 响应函数
function sendJson($data) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        exit;
    }
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 数据库连接
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    sendJson([
        'code' => 500,
        'message' => '数据库连接失败',
        'data' => null
    ]);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        if ($action == 'get_config') {
            try {
                // 获取配置项
                $stmt = $pdo->prepare("SELECT config_key, config_value FROM museum_config");
                $stmt->execute();
                $configs = $stmt->fetchAll();
                // 遍历数据
                $new_data = [];
                foreach ($configs as &$config) {
                    $new_data[$config['config_key']] = $config['config_value'];
                }
                
                sendJson([
                    'code' => 200,
                    'message' => '获取成功',
                    'data' => $new_data
                ]);
            } catch (Exception $e) {
                sendJson([
                    'code' => 500,
                    'message' => '获取配置失败: ' . $e->getMessage(),
                    'data' => null
                ]);
            }
        } else {
            sendJson([
                'code' => 400,
                'message' => '无效的操作',
                'data' => null
            ]);
        }
        break;
        
    case 'POST':
        if ($action == 'update_config') {
            try {
                $data = [];
                $data['advance_booking_days'] = $input['advance_booking_days'];
                $data['max_companions'] = $input['max_companions'];
                $data['venue_name'] = $input['venue_name'];
                $data['open_time'] = $input['open_time'];
                $data['address'] = $input['address'];
                $data['phone'] = $input['phone'];
                $data['email'] = $input['email'];
                $data['subway'] = $input['subway'];
                $data['bus'] = $input['bus'];
                $data['reservation_notice'] = $input['reservation_notice'];
                $data['enter_notice'] = $input['enter_notice'];

                foreach ($data as $key => $value) {
                    // 验证数值字段
                    if (in_array($key, ['advance_booking_days', 'max_companions'])) {
                        if (!is_numeric($value) || $value < 1) {
                            sendJson([
                                'code' => 400,
                                'message' => '可提前预约天数、最大同行人数必须是大于0的数字',
                                'data' => null
                            ]);
                        }
                    }

                    // 更新配置
                    $stmt = $pdo->prepare("UPDATE museum_config SET config_value = ? WHERE config_key = ?");
                    $result = $stmt->execute([$value, $key]);

                    if ($result) {
                        // 记录操作日志
                        $currentAdmin = getCurrentAdmin($pdo);
                        if ($currentAdmin) {
                            $configNames = [
                                'advance_booking_days' => '可提前预约天数',
                                'max_companions' => '最大同行人数',
                                'reservation_notice' => '预约说明',
                                'enter_notice' => '入场说明',
                                'venue_name' => '场馆名称',
                                'open_time' => '开放时间',
                                'address' => '地址',
                                'phone' => '电话',
                                'email' => '邮箱',
                                'subway' => '地铁',
                                'bus' => '公交',
                            ];
                            $configName = $configNames[$key] ?? $key;

                            // 对于富文本内容，只记录前100个字符
                            $displayValue = in_array($key, ['reservation_notice', 'enter_notice']) ?
                                mb_substr(strip_tags($value), 0, 100) . '...' :
                                $value;

                            logAdminOperation(
                                $pdo,
                                $currentAdmin[0],
                                $currentAdmin[1],
                                '系统配置修改',
                                'config',
                                "修改配置项「$configName」为：$displayValue",
                                ['config_key' => $key, 'config_value' => $displayValue]
                            );
                        }
                    }
                }
                sendJson([
                    'code' => 200,
                    'message' => '更新配置成功',
                    'data' => []
                ]);
                
            } catch (Exception $e) {
                sendJson([
                    'code' => 500,
                    'message' => '更新配置失败: ' . $e->getMessage(),
                    'data' => null
                ]);
            }
        } else {
            sendJson([
                'code' => 400,
                'message' => '无效的操作',
                'data' => null
            ]);
        }
        break;
        
    default:
        sendJson([
            'code' => 405,
            'message' => '不支持的请求方法',
            'data' => null
        ]);
}
?>